package com.zzw.basic.io.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class AIOServer {

    private static final int port = 30000;

    private static ByteBuffer readBuffer = ByteBuffer.allocate(1024);
    private static Charset utf = Charset.forName("utf-8");

    public static void main(String[] args) {
        try {
            AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open();
            server.bind(new InetSocketAddress(port));
            while (true){
                Future<AsynchronousSocketChannel> future = server.accept();
                AsynchronousSocketChannel socketChannel = future.get();
                socketChannel.write(ByteBuffer.wrap("hello".getBytes("UTF-8"))).get();
                readBuffer.clear();
                Integer length = socketChannel.read(readBuffer).get();
                readBuffer.flip();
                String content = utf.decode(readBuffer).toString();
                System.out.println(content);
                /*String msg = new String(readBuffer.array(),0,length);
                System.out.println(readBuffer.array().toString());*/
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
